package com.pkk.penguin.components.stater.exception.handler;

import com.pkk.components.rpc.response.CommonResponse;
import com.pkk.components.rpc.response.code.ErrorCode;
import com.pkk.components.rpc.response.util.ResponseUtil;
import com.pkk.penguin.components.oauth2.userdetails.exception.AuthUserException;
import com.pkk.penguin.components.oauth2.userdetails.exception.code.AuthoritiesCode;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * @author YuanWei
 * @description: 异常处理
 * @date 2019/4/15 17:22
 */
@Slf4j
@RestControllerAdvice
public class DefaultExceptionHandler {

  @ExceptionHandler(value = Throwable.class)
  public CommonResponse<?> exceptionHandler(Throwable exception) {
    log.error(exception.getMessage(), exception);
    return ResponseUtil.error(ErrorCode.FAIL);
  }

  @ExceptionHandler(value = Exception.class)
  public CommonResponse<?> exceptionHandler(Exception exception) {
    log.error(exception.getMessage(), exception);
    return ResponseUtil.error(ErrorCode.FAIL);
  }

  @ExceptionHandler(value = AccessDeniedException.class)
  public CommonResponse<Map<String, Object>> accessDeniedException(AccessDeniedException exception) {
    log.error("AccessDeniedException", exception);
    return ResponseUtil.error(AuthoritiesCode.NO_AUTHORITY);
  }

  @ExceptionHandler(value = AuthUserException.class)
  public CommonResponse<?> authClientException(AuthUserException exception) {
    log.error("AuthClientException", exception);
    return ResponseUtil.error(exception.getCodeEnum());
  }
}
